#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import re
import sys
import json
import logging
import time
import datetime
import struct
import subprocess
import traceback

from Ump.common import  log
from Ump.common import exception

from Ump.objs.db import models
from Ump.objs.manager_base import Manager
from Ump.objs.session_wrapper import enable_log_and_session, _sw

LOG = log.get_log('Ump.objs.snapshot.manager')

def add(x,y):
    return x + y


class SnapshotPolicyManager(Manager):
    MODEL = models.SnapshotPolicy

    def __init__(self):
        self.super_ = super(SnapshotPolicyManager, self)
        self.super_.__init__()

    @enable_log_and_session(resource='snap_policy', event='create')
    def create(self, _logger, kwargs):
        name = kwargs['name']
        
        _logger.update_props(oplog_obj=name, user_id=kwargs.get('op_user_id'))

        snapshot_policy = self._create(**kwargs)
        return snapshot_policy

    def _create(self, name, count, unit, username='admin', **kwargs):
        policy = self._get_policy(count, unit)
        user_id = _sw.get_user_id(username)

        values = {
            'snapshot_time': policy,
            'name': name, 
            'count': count, 
            'unit': unit,
            'user_id': user_id
        }

        get_snapshot = _sw.get_one(models.SnapshotPolicy,id_or_spec={'name':name})
        if get_snapshot:
            raise  exception.SnapshotPolicyNameExist('快照策略名称已存在')

        snapshot_policy = models.SnapshotPolicy(values).save()
        return snapshot_policy 
        
    @enable_log_and_session(resource='snap_policy', event='delete')
    def delete(self, _logger, kwargs):
        sp_id = kwargs['id']

        sp = self._get_one(sp_id)
        if sp.volumes:
            raise exception.ReferencedError('快照策略已关联卷')

        _logger.update_props(oplog_obj=sp.name, user_id=kwargs.get('op_user_id'))

        return sp.delete()

    @enable_log_and_session(resource='snap_policy', event='update')
    def update(self, _logger, kwargs):
        sp_id = kwargs.get('id')
        spolicy = self._get_one(sp_id)

        _logger.update_props(oplog_obj=spolicy.name, user_id=kwargs.get('op_user_id'))

        return self._update(spolicy, **kwargs)

    def _update(self, spolicy, name, count, unit, **kwargs):
        policy = self._get_policy(count, unit)

        values = {
            'snapshot_time': policy,
            'name': name, 
            'count': count, 
            'unit': unit
        }
        
        spolicy.update(values)
        return spolicy
        
    def _get_policy(self, count, unit):
        policy = ''

        if unit.startswith('hour'):
            policy = "%sh-1" % count
        elif unit.startswith('day'):
            policy = "%sd-1" % count
        elif unit.startswith('minute'):
            policy = "%sM-1" % count
        else:
            raise Exception("定时快照周期的单位错误")
        if not  policy :
            raise Exception("定时快照周期错误")
        return policy

    def _get_one(self, _id):
        snap_policy = _sw.get_one(models.SnapshotPolicy, id_or_spec=_id)
        if not snap_policy:
            raise exception.NotFound(_id=_id)

        return snap_policy


if __name__ == '__main__':
    snm = SnapshotPolicyManager()
